package com.fitness.front.service.impl.common;

import cn.hutool.json.JSONUtil;
import com.fitness.front.convertor.CourseConvertor;
import com.fitness.front.modal.course.entity.Course;
import com.fitness.front.modal.course.vo.CourseVO;
import com.fitness.front.modal.response.ServerResponseEntity;
import com.fitness.front.service.ICourseService;
import com.fitness.front.utils.HttpUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
@RequiredArgsConstructor
public class RecommenderServiceImpl {

    private static final String RECOMMENDER_URL = "http://localhost:9086/api/v1/recommender/alsRecommender";

    private static final String PLAN_RECOMMENDER_URL = "http://localhost:9086/api/v1/recommender/randomForest";

    private final ICourseService courseService;
    private final CourseConvertor courseConvertor;

    public List<CourseVO> recommend(Long userId, Long courseId) {
        try {
            InputStream is = HttpUtils.doGet(RECOMMENDER_URL + "?userId=" + userId + "&courseId=" + courseId).getContent();
            String s = new String(is.readAllBytes(), StandardCharsets.UTF_8);
            ServerResponseEntity<List<Long>> courseIds = JSONUtil.toBean(s, ServerResponseEntity.class);
            List<Course> courses = courseService.listByIds(courseIds.getData());
            return courseConvertor.entities2Vos(courses);
        } catch (IOException e) {
            log.error("获取推荐课程失败:",e);
        }
        return null;
    }

    public Map<String,Number> recommendPlan(Integer age, Integer gender,Double height,Double weight,Integer level) {
        try {
            Map<String,Number> data = new HashMap<>();
            data.put("age",age);
            data.put("weight", weight);
            data.put("height", height);
            data.put("gender", gender);
            data.put("experience_level", level);
            String s = new String(HttpUtils.doHttpPost(PLAN_RECOMMENDER_URL,JSONUtil.toJsonStr(data)).getBytes(StandardCharsets.UTF_8));
            Map<String,Object> retData = JSONUtil.toBean(s, Map.class);
            log.info("recommendPlanData:{}",retData);
            return (Map<String, Number>) retData.get("data");
        }catch (Exception e) {
            log.error("生成推荐计划失败：", e);
        }
        return null;
    }
}
